<?php
/*
*dao代码生成器
*shineli
*2009-8-22
*/

//配置
define('HOST','127.0.0.1');
define('USER','crazysperm');
define('PASSWORD','juventus1314');
define('DBNAME','test');
define('DIR','d:/dao/');
define('ROWS',0);
define('CHARSET','utf8');

class Database{
	var $host;
	var $user;
	var $password;
	var $schema_database;
	var $dblink;
	var $query;
	var $result;
	var $rows;

	function Database()
	{
		$this->host = HOST;
		$this->user = USER;
		$this->password = PASSWORD;
		$this->schema_database = 'information_schema';
		$this->rows = ROWS;
	}

	function open_db()
	{
		$this->dblink = @mysql_connect($this->host,$this->user,$this->password) or die ('连接数据库错误');
		mysql_query("SET NAMES '".CHARSET."'");
	}

	function select_db()
	{

		@mysql_select_db($this->schema_database,$this->dblink) or die ('选择数据库失败');

	}

	function close_db()
	{
		mysql_close();
	}

	function query($query)
	{
		$this->open_db();
		$this->select_db();
		$this->query = $query;
		$this->result = mysql_query($query,$this->dblink) or die ('执行sql语句失败');
		if(ereg("SELECT",$query))
		{
			$this->rows = mysql_num_rows($this->result);
		}

		$this->close_db();
	}

	function get_tables_of_db($dbname)
	{
		$query ="select * from TABLES where TABLE_SCHEMA ='".$dbname."'";
		$this->query($query);
	}

	function get_columns_of_table($tablename,$dbname)
	{
		$query ="select * from COLUMNS where TABLE_SCHEMA ='".$dbname."' and TABLE_NAME ='".$tablename."' order by ORDINAL_POSITION";
		$this->query($query);
	}
}
$database = new Database();
$database->open_db();
$database->get_tables_of_db(DBNAME);
$tablelist = $database->result;
//遍历表
while($table = mysql_fetch_array($tablelist))
{
	//------------------
	//生成数据层代码文件
	//------------------
	$dir = DIR.'data';
	if(!is_dir($dir))
	{
		mkdir($dir);
	}
	$filename = $dir."/" .$table['TABLE_NAME'].".php";
	if(file_exists($filename))
	{
		unlink($filename);
	}
	$file = fopen($filename, 'w+');
	$filedate = date("Y-m-d");

	$content = "";
	$content = '<?php
/*
* -------------------------------------------------------
* FILE NAME:        '.$table['TABLE_NAME'].'.php
* GENERATION DATE:  '.$filedate.'
* FOR MYSQL TABLE:  '.$table['TABLE_NAME'].'
* FOR MYSQL DB:     '.DBNAME.'
* TABLE COMMENT:    '.$table['TABLE_COMMENT'].'
* -------------------------------------------------------
*/
include_once(DAO_PATH.\'/dao_tables.php\');
';
	$content.='
global $metastr;
global $metanum;
global $'.$table['TABLE_NAME'].';


';

	$database->get_columns_of_table($table['TABLE_NAME'],DBNAME);
	$columnlist =$database->result;
	while($column = mysql_fetch_array($columnlist))
	{
		$content.='
//COLUMN NAME: '.$column['COLUMN_NAME'].' | COLUMN COMMENT: '.$column['COLUMN_COMMENT'].'
//COLUMN TYPE: '.$column['COLUMN_TYPE'].' | COLUMN DEFAULT: '.$column['COLUMN_DEFAULT'].' | NULLABLE: '.$column['IS_NULLABLE'].' | COLUMN KEY: '.$column['COLUMN_KEY'].' | EXTRA:'.$column['EXTRA'];
		$content.='
$'.$table['TABLE_NAME'].'[\''.$column['COLUMN_NAME'].'\'] = ';
		if($column['DATA_TYPE']=='int'||$column['DATA_TYPE']=='smallint'||$column['DATA_TYPE']=='tinyint'||$column['DATA_TYPE']=='mediumint'||$column['DATA_TYPE']=='bigint'||$column['DATA_TYPE']=='decimal'||$column['DATA_TYPE']=='double'||$column['DATA_TYPE']=='float')
		{
			$content.='$metanum;
			
			';
		}
		else
		{
			$content.='$metastr;
			
			';
		}
	}
	$content.='
//GENERATE END 
?>';
	fwrite($file, $content);
	echo $table['TABLE_NAME'].'数据层代码生成成功,路径：'.$filename.'<br/>';


	//------------------
	//生成数据访问层代码文件
	//------------------
	$dir = DIR."/dataaccess";
	if(!is_dir($dir))
	{
		mkdir($dir);
	}
	$filename = $dir."/b_" .substr($table['TABLE_NAME'],2)."_access.php";
	if(file_exists($filename))
	{
		unlink($filename);
	}
	$file = fopen($filename, 'w+');
	$content = "";
	$content = '<?php
/*
* -------------------------------------------------------
* FILE NAME:        b_'.substr($table['TABLE_NAME'],2).'_access.php
* GENERATION DATE:  '.$filedate.'
* FOR MYSQL TABLE:  '.$table['TABLE_NAME'].'
* FOR MYSQL DB:     '.DBNAME.'
* TABLE COMMENT:    '.$table['TABLE_COMMENT'].'
* -------------------------------------------------------
*/

include_once(DAO_PATH.\'dao_base.php\');
include_once(DATA_PATH.\''.$table['TABLE_NAME'].'.php\');

global $dao_'.substr($table['TABLE_NAME'],2).'_access;

if($dao_'.substr($table['TABLE_NAME'],2).'_access==NULL)
{
	global $'.$table['TABLE_NAME'].';
	$dao_'.substr($table['TABLE_NAME'],2).'_access = new DAO();
	$dao_'.substr($table['TABLE_NAME'],2).'_access->init(DBNAME_DEFAULT,\''.$table['TABLE_NAME'].'\',$'.$table['TABLE_NAME'].',$'.$table['TABLE_NAME'].');
}

//--------------------------------------------------------
//create
//--------------------------------------------------------
';

	$database->get_columns_of_table($table['TABLE_NAME'],DBNAME);
	$columnlist =$database->result;
	$prikeys = array();
	while($column = mysql_fetch_array($columnlist))
	{
		if($column['COLUMN_KEY']=='PRI')
		{
			array_push($prikeys,$column);
		}
	}
	$content.='

/*
 *	@param $data 数组 
 *	@param $msg	返回操作信息
 *	成功插入的记录数组中会有最近插入的主键
*/
function f_'.substr($table['TABLE_NAME'],2).'_create(&$data,&$msg)
{
	$ret = 0;
	global $dao_'.substr($table['TABLE_NAME'],2).'_access;
	$ret = $dao_'.substr($table['TABLE_NAME'],2).'_access->insert($data,$msg);
	//测试时，记录新纪录的主键
	if($ret==0)
	{
		DAO_Log::debug("create '.substr($table['TABLE_NAME'],2).' success ';
	foreach($prikeys as $prikey)
	{
		$content.=' '.$prikey['COLUMN_NAME'].':$data['.$prikey['COLUMN_NAME'].'] ';
	}
	$content.='");
	}
	return $ret;
}

//--------------------------------------------------------
//query
//--------------------------------------------------------

';

	if(sizeof($prikeys)>0)
	{
		$content.='
/*';
		foreach($prikeys as $prikey)
		{
			$content.='
@param	$'.$prikey['COLUMN_NAME'].' '.$prikey['COLUMN_COMMENT'];
		}
		$content.='
	 
@param	&$data	保存返回的结果集
错误返回 -1
正确返回 0
*/
function f_get_'.substr($table['TABLE_NAME'],2).'_by_pk(';
		foreach($prikeys as $prikey)
		{
			$content.='$'.$prikey['COLUMN_NAME'].',';
		}
		$content.='&$data)
{
	global $dao_'.substr($table['TABLE_NAME'],2).'_access;
	if(';
		$s = '';
		foreach($prikeys as $prikey)
		{
			$s.='||!is_numeric($'.$prikey['COLUMN_NAME'].')';
		}
		$s = trim($s,'||');
		$content.=$s.')
	{
		return -1;
	}';
		foreach($prikeys as $prikey)
		{
			$content.='
	$data_where[\''.$prikey['COLUMN_NAME'].'\'] = $'.$prikey['COLUMN_NAME'].';';
		}
		$content.='
	$ret = $dao_'.substr($table['TABLE_NAME'],2).'_access->query($data_where,$data,$msg);
	if($ret == 0 && sizeof($data) == 1)
	{
		DAO_Log::debug(__FUNCTION__." success from dbconnection :".$dao_'.substr($table['TABLE_NAME'],2).'_access->dbconn_name );			
	}
	else
	{
		DAO_Log::error(__FUNCTION__." error  from dbconnection :".$dao_'.substr($table['TABLE_NAME'],2).'_access->dbconn_name.",return=$ret,msg=$msg,recordcount=".sizeof($data));			
	}
	return $ret;
}	
';
	}
	$content.='

/*
根据其他查询条件获取report结果集
@param $data_where array 查询条件
@param $ex_sql	order by,group by 语句
@param @limit	limit语句
@param $data	返回的结果集
@param	$msg	记录查询错误信息
*/
function f_get_'.substr($table['TABLE_NAME'],2).'_by(&$data_where,$ex_sql,$limit,&$data,&$msg)
{
	global $dao_'.substr($table['TABLE_NAME'],2).'_access;
	$dao_'.substr($table['TABLE_NAME'],2).'_access->ex_sql = $ex_sql;
	$dao_'.substr($table['TABLE_NAME'],2).'_access->query_limit = $limit;
	return $dao_'.substr($table['TABLE_NAME'],2).'_access->query($data_where,$data,$msg);
}


//--------------------------------------------------------
//modify
//--------------------------------------------------------

/*
@param $data 更新的值
@param $data_where 更新条件
*/
function f_'.substr($table['TABLE_NAME'],2).'_modify(&$data,&$data_where,$msg)
{
	global $dao_'.substr($table['TABLE_NAME'],2).'_access;
	return $dao_'.substr($table['TABLE_NAME'],2).'_access->update($data,$data_where,$msg);
}

?>
';
	fwrite($file, $content);
	echo $table['TABLE_NAME'].'数据访问层代码生成成功,路径：'.$filename.'<br/>';
}

?>